'use client';

import React, { useState, useEffect } from "react";
import { LeftOutlined, UploadOutlined } from "@ant-design/icons";
import { Card, Button, Input, Modal, Form } from "antd";
import { Upload, message, Avatar } from "antd";
import { useRouter } from "next/navigation";
import { useUser } from "../../../context/userContext";
import api from "../../../utils/api";
import styles from '@/components/Font.module.css';

// 用户类型定义
interface User {
  id: string;
  username: string;
  email: string;
  display_name: string;
  bio: string;
  role: string;
  icon: string;
  access_token: string;
  password?: string;
}

// 表单值类型定义
interface FormValues {
  display_name: string;
  bio: string;
  password: string;
}

export default function EditProfilePage() {
  const [form] = Form.useForm<FormValues>();
  const router = useRouter();
  const { user, setUser } = useUser();
  const userId = user.id;
  const accessToken = user ? user.access_token : "";
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [isErrorModalVisible, setIsErrorModalVisible] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const username = user ? user.display_name : "请输入展示名称";
  const bio = user ? user.bio : "请输入个性签名";
  const [avatarUrl, setAvatarUrl] = useState(user?.icon || "");
  const [isMobile, setIsMobile] = useState(false);
  const [screenHeight, setScreenHeight] = useState(window.innerHeight);

  // 计算可用内容高度
  const contentHeight = screenHeight - 120; // 减去顶部和底部边距

  useEffect(() => {
    setAvatarUrl(user.icon);
    console.log("edit userdisplayname: ", username);
    
    // 检测屏幕尺寸和高度
    const checkScreen = () => {
      setIsMobile(window.innerWidth < 768);
      setScreenHeight(window.innerHeight);
    };
    
    checkScreen();
    window.addEventListener('resize', checkScreen);
    
    return () => {
      window.removeEventListener('resize', checkScreen);
    };
  }, [user]);

  // 取消修改
  const handleCancel = () => {
    router.back();
    setErrorMessage("您已取消修改");
    setIsErrorModalVisible(true);
  };

  // 确认修改的提示弹窗
  const showConfirmModalHandler = () => {
    setShowConfirmModal(true);
  };

  // 确认修改
  const handleConfirm = async () => {
    form
      .validateFields()
      .then(async (values: FormValues) => {
        const homeuser: User = { ...user };

        if (values.display_name !== undefined && values.display_name !== "") {
          homeuser.display_name = values.display_name;
        }
        if (values.bio !== undefined && values.bio !== "") {
          homeuser.bio = values.bio;
        }
        if (values.password !== undefined && values.password !== "") {
          homeuser.password = values.password;
        }
        if (
          homeuser.display_name === null ||
          homeuser.display_name === "" ||
          homeuser.display_name === undefined
        ) {
          homeuser.display_name = "momo";
        }
        if (
          homeuser.bio === null ||
          homeuser.bio === "" ||
          homeuser.bio === undefined
        ) {
          homeuser.bio = "Ciallo～(∠・ω< )⌒★";
        }
        
        try {
          console.log(homeuser);
          const response = await api.post(
            "/users/info",
            {
              username: homeuser.username,
              email: homeuser.email,
              password: homeuser.password,
              display_name: homeuser.display_name,
              bio: homeuser.bio,
            },
            {
              headers: {
                Authorization: `Bearer ${accessToken}`,
              },
            }
          );

          if (response.status === 201) {
            setUser(homeuser);
            localStorage.setItem("user", JSON.stringify(homeuser));

            setErrorMessage("修改成功");
            setIsErrorModalVisible(true);
            router.back();
          } else if (response.status === 403) {
            setErrorMessage("无权限修改用户信息");
            setIsErrorModalVisible(true);
          } else if (response.status === 404) {
            setErrorMessage("用户不存在");
            setIsErrorModalVisible(true);
          } else {
            setErrorMessage("更新失败，请稍后再试");
            setIsErrorModalVisible(true);
          }
        } catch (error) {
          console.error(error);
          if ((error as any).response) {
            if ((error as any).response.status === 401) {
              setErrorMessage("认证失败，您没有权限修改");
            } else if ((error as any).response.status === 500) {
              setErrorMessage("服务器错误，请稍后再试");
            } else {
              setErrorMessage(
                (error as any).response.data.message || "请求失败，请稍后再试"
              );
            }
          } else if ((error as any).request) {
            setErrorMessage("网络错误，请检查您的网络连接");
          } else {
            setErrorMessage("请求设置错误，请稍后再试");
          }
          setIsErrorModalVisible(true);
        }
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
        setErrorMessage("修改失败，请检查输入内容");
        setIsErrorModalVisible(true);
      });
    setShowConfirmModal(false);
  };

  // 取消确认修改
  const handleConfirmCancel = () => {
    setShowConfirmModal(false);
  };

  // 上传头像的函数
  const uploadAvatar = async (file: File) => {
    const isImage = [
      "image/jpeg",
      "image/png",
      "image/gif",
      "image/webp",
    ].includes(file.type);
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isImage) {
      throw new Error("只能上传 JPG/PNG/GIF/WEBP 格式的图片");
    }
    if (!isLt5M) {
      throw new Error("图片大小不能超过 5MB");
    }

    const formData = new FormData();
    formData.append("file", file);
    const response = await api.post(`/media/avatar?id=${userId}`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: `Bearer ${accessToken}`,
      },
    });
    if (!response.data.success) {
      throw new Error("上传头像失败，请稍后再试");
    }

    const userInfo = await api.get("/users/info", {
      params: { id: userId },
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });

    const newUser: User = { ...user, icon: userInfo.data.icon };
    setUser(newUser);
    setAvatarUrl(userInfo.data.icon);
  };

  return (
    <div className={`bg-[#F4EDEB] p-4 md:p-6 min-h-screen flex flex-col items-center justify-start`}>
      {/* 返回图标 */}
      <div className="mb-4 md:mb-6 flex justify-start items-center text-[#7A6E6E] w-full max-w-4xl px-2">
        <LeftOutlined className="text-2xl cursor-pointer hover:text-[#D6A7A1] transition-colors" onClick={handleCancel} />
      </div>

      {/* 整合内容卡片 */}
      <div className="bg-white/60 backdrop-blur-md rounded-3xl shadow-md p-4 md:p-6 transition-all hover:shadow-lg max-w-4xl w-full mx-auto">
        <h2 className={`${styles.titlesmall} text-xl md:text-2xl mb-4 text-[#7A6E6E]`}>编辑个人资料</h2>
        
        {/* 整合头像和资料区域 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          {/* 左侧：头像上传区域 */}
          <div className="md:col-span-1 flex flex-col items-center justify-center">
            <Avatar
              size={isMobile ? 90 : 120}
              src={`http://120.26.138.4:3000${avatarUrl}`}
              className="shadow-md rounded-full border-4 border-white mb-4"
            />
            <Upload
              showUploadList={false}
              customRequest={async (options) => {
                const { file, onError } = options;
                try {
                  uploadAvatar(file as File);
                } catch (err: any) {
                  message.error(err.message || "上传失败，请稍后再试");
                  onError?.(err);
                }
              }}
            >
              <Button 
                className="bg-[#E8D6D0] hover:bg-[#D6A7A1] text-[#7A6E6E] hover:text-white rounded-full px-4 py-1.5 text-sm transition-all shadow-md hover:shadow-lg"
                icon={<UploadOutlined />}
              >
                上传图片
              </Button>
            </Upload>
          </div>
          
          {/* 右侧：资料编辑区域 */}
          <div className="md:col-span-3">
            <Form
              form={form}
              layout="vertical"
              initialValues={{
                display_name: username || "",
                bio: bio || "",
              }}
              className="space-y-4"
            >
              <Form.Item 
                label={<span className={styles.text}>展示名称</span>} 
                name="display_name"
                className={styles.text}
                rules={[{ required: true, message: '请输入展示名称' }]}
              >
                <Input 
                  className="rounded-lg border-[#E8D6D0] focus:border-[#D6A7A1] focus:ring-1 focus:ring-[#D6A7A1] transition-all bg-white/80" 
                  placeholder="请输入展示名称"
                />
              </Form.Item>

              <Form.Item 
                label={<span className={styles.text}>个性签名</span>} 
                name="bio"
                className={styles.text}
              >
                <Input.TextArea 
                  rows={2} 
                  className="rounded-lg border-[#E8D6D0] focus:border-[#D6A7A1] focus:ring-1 focus:ring-[#D6A7A1] transition-all bg-white/80"
                  placeholder="请输入个性签名"
                />
              </Form.Item>

              <Form.Item
                label={<span className={styles.text}>修改密码</span>}
                name="password"
                rules={[{ min: 5, message: "密码至少5位" }]}
                className={styles.text}
              >
                <Input.Password 
                  placeholder="请输入新的密码（不修改则留空）" 
                  className="rounded-lg border-[#E8D6D0] focus:border-[#D6A7A1] focus:ring-1 focus:ring-[#D6A7A1] transition-all bg-white/80"
                />
              </Form.Item>

              <div className="flex justify-end gap-3 mt-6">
                <Button
                  className="bg-white border border-[#D6A7A1] text-[#D6A7A1] hover:bg-[#F4EDEB] font-medium rounded-full px-5 py-1.5 text-sm transition-all shadow-md hover:shadow-lg"
                  onClick={handleCancel}
                >
                  取消
                </Button>
                <Button 
                  type="primary" 
                  className="bg-[#D6A7A1] hover:bg-[#C19A8C] text-white font-medium rounded-full px-5 py-1.5 text-sm transition-all shadow-md hover:shadow-lg"
                  onClick={showConfirmModalHandler}
                >
                  确认
                </Button>
              </div>
            </Form>
          </div>
        </div>
      </div>

      {/* 底部留白 */}
      <div className="h-8 w-full"></div>

      {/* 确认修改弹窗 */}
      <Modal
        title="确认修改"
        visible={showConfirmModal}
        onCancel={handleConfirmCancel}
        onOk={handleConfirm}
        okText="确认"
        cancelText="取消"
        okButtonProps={{ className: "bg-[#D6A7A1] hover:bg-[#C19A8C] text-white font-medium rounded-full px-6 py-2 transition-all shadow-md hover:shadow-lg" }}
        cancelButtonProps={{ className: "bg-white border border-[#D6A7A1] text-[#D6A7A1] font-medium rounded-full px-6 py-2 transition-all shadow-md hover:shadow-lg" }}
      >
        <p className="text-[#7A6E6E]">确定要保存修改吗？</p>
      </Modal>

      {/* 错误提示弹窗 */}
      <Modal
        title="提示"
        visible={isErrorModalVisible}
        onCancel={() => setIsErrorModalVisible(false)}
        footer={[
          <Button 
            key="close" 
            onClick={() => setIsErrorModalVisible(false)}
            className="bg-[#D6A7A1] hover:bg-[#C19A8C] text-white font-medium rounded-full px-6 py-2 transition-all shadow-md hover:shadow-lg"
          >
            关闭
          </Button>,
        ]}
      >
        <div className="text-[#7A6E6E]">{errorMessage}</div>
      </Modal>
    </div>
  );
}
